require('./review.css');
import {
    getReviewList,
    review,
    cancleReview
} from './ajax';
$(function () {
    $.init();
    let loading = false;

    $('.list-tab').click(function () {

        if ($('.infinite-scroll-preloader').length <= 0) {
            $('.content').append(renderLoading());
            $.attachInfiniteScroll($('.infinite-scroll'));
        }
        loading = true;
        $('.infinite-scroll-preloader').show();
        $(this).addClass('active').siblings().removeClass('active');
        let status = $(this).data('status');
        status == 0 ? $('#review').text("审核").attr('data-review',"0"):$('#review').text("取消审核").attr('data-review',"1");

        getReviewList(status, 0, (res) => {
            loading = false;
            $('.infinite-scroll-preloader').hide();
            $(this).data('page', 1);
            $('.list-container').html(renderListItem(res));
            $('.list-block ul.list-container').css("margin-bottom","63px");
            $('.check').iCheck({
                checkboxClass: 'iradio_square-blue'
            });
            $('.checkall .checked').removeClass('hover');
            $('.checkall .checked').removeClass('checked');
            $('.checkall input').prop('checked', false);
            $('.check').on('ifChanged', function () {
                computeTotalMoney();
                if (isAllChecked()) {
                    $('.checkall .iradio_square-blue').addClass('checked');
                    $('.checkall .iradio_square-blue').addClass('hover');
                    $('.checkall input').prop('checked', true);

                } else {
                    $('.checkall .checked').removeClass('hover');
                    $('.checkall .checked').removeClass('checked');
                    $('.checkall input').prop('checked', false);
                }
            });
        });
    });
    $('.list-tab').eq(0).trigger('click');

    $(document).on('infinite', '.infinite-scroll-bottom', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        $('.infinite-scroll-preloader').show();
        let activeTab = $('.list-tab-box .active');
        let status = activeTab.data('status');
        let page = activeTab.data('page');
        getReviewList(status, page, (res) => {
            loading = false;
            $('.infinite-scroll-preloader').hide();
            if (res.length <= 0) {
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').remove();
                 $('.list-block ul.list-container').css("margin-bottom","63px");
                return;
            }
            activeTab.data('page', page + 1);
            $('.list-container').append(renderListItem(res));
            $('.check').iCheck({
                checkboxClass: 'iradio_square-blue'
            });
            $('.check').on('ifChanged', function () {
                computeTotalMoney();
                if (isAllChecked()) {
                    $('.checkall .iradio_square-blue').addClass('checked');
                    $('.checkall .iradio_square-blue').addClass('hover');
                    $('.checkall input').prop('checked', true);

                } else {
                    $('.checkall .checked').removeClass('hover');
                    $('.checkall .checked').removeClass('checked');
                    $('.checkall input').prop('checked', false);
                }
            });
            $('.checkall').iCheck('uncheck');
        });

    });
    //全选按钮
    $('.checkall').iCheck({
        checkboxClass: 'iradio_square-blue'
    });

    $('.checkall').on('ifChecked', function (e) {
        $('.check').iCheck('check');
        let receiv = 0,
            pay = 0;
        $('.item-receive').each(function () {
            receiv += parseFloat($(this).text());
        });
        $('.item-pay').each(function () {
            pay += parseFloat($(this).text());
        });
        $(".receive").text(receiv);
        $(".pay").text(pay);
    });
    $('.checkall').on('ifUnchecked', function (e) {
        $('.check').iCheck('uncheck');
        $(".receive").text(0);
        $(".pay").text(0);
    });

    $("#review").click(function () {
        let str = $('input[type="checkbox"]:checked').map(function () {
            return $(this).val()
        }).get().join(",");
        review($(this).data('review'),str, (res) => {
            if (res.rel == 1) {
                $.toast(res.msg);
                location.reload();
            } else {
                $.toast(res.msg);
            }
        });
    })

});

//计算总价
const computeTotalMoney = () => {
    let parentDOM = $('.item-content input:checked').parents('.item-content');


    let receiveArr = parentDOM.map(function () {
        let receiveData = parseFloat($(this).find('.item-receive').text()).toFixed(2);
        return receiveData;
    }).get();
    let payArr = parentDOM.map(function () {
        let payData = parseFloat($(this).find('.item-pay').text()).toFixed(2);
        return payData;
    }).get();


    let receiv = 0;
    receiveArr.forEach(val => {
        receiv += parseFloat(val);
    });
    let pay = 0;
    payArr.forEach(val => {
        pay += parseFloat(val);
    });

    $(".receive").text(receiv);
    $(".pay").text(pay);

};


//全选勾选状态
const isAllChecked = () => {

    let allLength = $('.item-content').get().length;
    let checkLength = $('.item-content input:checked').length;
    if (checkLength < allLength) {
        return false;
    }
    return true;
};

const renderListItem = (data) => {

    let review = $.map(data, function (val) {

            let level1;
        switch (parseInt(val.user_level)) {
            case 1:
                level1 = `[总代]`;
                break;
            case 2:
                level1 = `[一级代理]`;
                break;
            case 3:
                level1 = `[二级代理]`;
                break;
            default:
                level1 = ``;
                break;
        }
        let receive=Number(val.should_receiv)+Number(val.shipping_fee);
        let pay=Number(val.should_pay)+Number(val.shipping_fee);
        let fee=Number(val.shipping_fee);

        let item = `
                     <li>
                            <div class="list-block media-list tabList add-arrow">
                                <div class="label-checkbox item-content ">
                                        <div class="check">
                                             <input type="checkbox" name="my-checkbox" value='${val.order_id}'> 
                                        </div>                      
                                        <div class="item-media"><i class="icon icon-form-checkbox"></i></div>
                                         <div class="item-inner">    
                                            <div class="item-subtitle">订单编号：<span>${val.order_sn}</span></div>
                                            <div class="item-subtitle">下单时间：<span>${val.add_time}</span></div>
                                            <div class="item-subtitle">下单代理：<span>${level1}${val.username}</span></div>
                                            <div class="item-subtitle">应收：<span>￥<b class="item-receive">${receive}</b></span>（含运费<span>￥<b class="item-receive">${fee}</b></span>）</div>
                                            <div class="item-subtitle">应付：<span>￥<b class="item-pay">${pay}</b></span>（含运费<span>￥<b class="item-receive">${fee}</b></span>）</div>
                                         </div>
                                    </div>
                            </div>
                        </li>
    `;
        return item;
    });
    return review.join('');
};

const renderLoading = () => {
    return `
    <div class="infinite-scroll-preloader">
        <div class="preloader"></div>
    </div>
    `;
}